package longrise.phone.com.bjjt_henan.main;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;

/**
 * 轮播图片的视图
 */
public class RollImageView extends LFView implements ViewPager.OnPageChangeListener {

    private View view;

    private Context context;

    private ViewPager viewPager;//轮播控件

    private ImageAdapter adapter;

    private LinearLayout dotLayout;//轮播点集合

    private List<ImageView> picLists;//轮播图片集合

    private Timer timer;

    private TimerTask timerTask;

    private int curItem;

    private String newsType;//新闻类型

    private View.OnClickListener listener;

    public RollImageView(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter parameter = new FormParameter();
        parameter.setShowtitle(false);
        return parameter;
    }

    @Override
    public View getView() {
        return view;
    }

    public void setNewsType(String newsType) {
        this.newsType = newsType;
    }

    @Override
    public void init() {
        if (null == context) {
            return;
        }
        view = LayoutInflater.from(context).inflate(R.layout.view_rollimage, null);
        if (null == view) {
            return;
        }
        viewPager = (ViewPager) view.findViewById(R.id.rollimage_viewpager);
        dotLayout = (LinearLayout) view.findViewById(R.id.rollimage_layout_dot);

        adapter = new ImageAdapter();
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
    }

    public void setListener(View.OnClickListener listener) {
        this.listener = listener;
    }

    private void addDefault() {
        EntityBean bean = new EntityBean();
        bean.set("imgtitle", "drawable://" + R.mipmap.banner_peccancy);

        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setOnClickListener(listener);
        imageView.setTag(bean);
        picLists.add(imageView);
        imageView = null;

        View view = new View(context);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UiUtil.dip2Px(8), UiUtil.dip2Px(8));
        view.setLayoutParams(params);
        view.setBackgroundResource(R.drawable.selector_dot);
        dotLayout.addView(view);
        view = null;
    }

    //显示轮播效果图
    private void showImgView(EntityBean[] beans) {
        if (view == null) {
            return;
        }
        stopTimer();
        if (null == picLists) {
            picLists = new ArrayList<ImageView>();
        } else {
            picLists.clear();
        }
        dotLayout.removeAllViews();
        addDefault();
        //实例化指示点
        for (int i = 0; i < beans.length; i++) {
            //图片
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setTag(beans[i]);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EntityBean bean = (EntityBean) v.getTag();
                    if (bean == null) {
                        return;
                    }
                    Intent cintent = new Intent(context, CarNewsActivity.class);
                    cintent.putExtra("databean", bean);
                    context.startActivity(cintent);
                }
            });
            picLists.add(imageView);
            imageView = null;
            //点
            View view = new View(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UiUtil.dip2Px(8), UiUtil.dip2Px(8));
//            if (i != 0) {
            params.leftMargin = 20;
//            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.selector_dot);
            dotLayout.addView(view);
            view = null;
        }
        adapter.notifyDataSetChanged();
        if (dotLayout.getChildCount() <= 1) {//只有一张图时不显示滚动点
            dotLayout.setVisibility(View.INVISIBLE);
        } else {
            dotLayout.setVisibility(View.VISIBLE);
            updateCurDot(curItem);
            startTimer();
        }
    }

    private void startTimer() {
        if (null == timer) {
            timer = new Timer();
        }
        if (null == timerTask) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (null != mhandler) {
                        mhandler.sendEmptyMessage(0);
                    }
                }
            };
        }
        timer.schedule(timerTask, 3000, 3000);
    }

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (view == null) {
                return;
            }
            curItem++;
            if (curItem >= picLists.size()) {
                curItem = 0;
            }
            viewPager.setCurrentItem(curItem);
            updateCurDot(curItem);
        }
    };

    private void stopTimer() {
        if (null != timerTask) {
            timerTask.cancel();
            timerTask = null;
        }
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onPageSelected(int position) {
        updateCurDot(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    /**
     * 更新选中点
     */
    private void updateCurDot(int pos) {
        for (int i = 0; i < dotLayout.getChildCount(); i++) {
            dotLayout.getChildAt(i).setEnabled(i == pos);
        }
    }

    private DisplayImageOptions options;

    //实例化imageloader的参数
    public DisplayImageOptions getOptions() {
        if (null == options) {
            DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
            builder.showImageForEmptyUri(R.mipmap.banner);
            builder.showImageOnFail(R.mipmap.banner);
            builder.showImageOnLoading(R.mipmap.reflash);
            builder.cacheInMemory(true);
            builder.cacheOnDisk(true);
            builder.imageScaleType(ImageScaleType.EXACTLY_STRETCHED);
            options = builder.build();
        }
        return options;
    }

    private class ImageAdapter extends PagerAdapter {

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getCount() {
            return (null == picLists) ? 0 : picLists.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = picLists.get(position);
            String imgUrl = ((EntityBean) imageView.getTag()).getString("imgtitle");
            ImageLoader.getInstance().displayImage(imgUrl, imageView, getOptions());
            container.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public void refresh() {
        BaseApplication application = ((MainActivity) context).getAppData();
        String userflag = application.getKckpName();
        String token = application.getToken();
        ApiImpI.getInstance(context).searchNews(userflag, token, newsType, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {

            }

            @Override
            public void onSuccess(Object result) {
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    EntityBean[] beans = bean.getBeans("data");
                    if (beans != null && beans.length > 0) {
                        showImgView(beans);
                    }
                }
            }
        });
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        stopTimer();
        if (null != viewPager) {
            viewPager.setOnPageChangeListener(null);
            viewPager.setAdapter(null);
            viewPager = null;
        }
        if (null != picLists) {
            picLists = null;
        }
        if (null != dotLayout) {
            dotLayout.removeAllViews();
            dotLayout = null;
        }
        mhandler = null;
        view = null;
    }
}
